<?php if( !defined( 'MAIN_DIR' ) ) { header( 'Location: ' . dirname( PHP_SELF ) . '/' ); exit( ); }
	/**
	 * Copyright(c) 2006-2009, Nelson Daza, <nelson.daza@gmail.com>
	 * All rights reserved.
	**/
	error_reporting( E_ALL | E_STRICT );
	
	// Avoid WARNING when no date.timezone set
	if( !ini_get( 'date.timezone' ) )
		ini_set( 'date.timezone', 'America/Bogota' );
	
	if( version_compare( PHP_VERSION, '5.0.0', '<' ) )
		finalError( 'Minimum required interpreter 5.0.0 not found.<br />Actually using ' . PHP_VERSION );
	
	if( !defined( 'E_STRICT' ) )
		define( 'E_STRICT', -1 );

	define ( 'DS', DIRECTORY_SEPARATOR );
	
	/**
	 * String transformations
	**/
	define( 'ACL_MODIFY',	1 );
	define( 'ACL_CREATE',	2 );
	define( 'ACL_DELETE',	4 );
	define( 'ACL_ALL',		7 );
	
	require_once( dirname( __FILE__ ) . DS . 'config.inc.php' );
	
	define ( 'SWAT_VERSION', '2.7.18' );
	define ( 'SWAT_TYPE', 'Lite' );
	
	if( !defined( 'SITE_NAME' ) )
		define ( 'SITE_NAME', 	'NEW SITE' );
	if( !defined( 'MIT' ) )
		define ( 'MIT', true );
		
	if( !defined( 'BASE_DIR' ) )
		define ( 'BASE_DIR', dirname( dirname( dirname( __FILE__ ) ) ) . DS );
	if( !defined( 'SWAT_DIR' ) )
		define ( 'SWAT_DIR', BASE_DIR . 'SWAT' . DS );
	if( !defined( 'USE_CACHE' ) )
		define ( 'USE_CACHE', true );
	if( !defined( 'CACHE_TIME' ) )
		define ( 'CACHE_TIME', 60 * 60 * 24 * 7 );	// 7 Days
	if( !defined( 'SWAT_CACHE_DIR' ) )
		define ( 'SWAT_CACHE_DIR', SWAT_DIR . 'cache' . DS );
	if( !defined( 'UPLOADS_DIR' ) )
		define ( 'UPLOADS_DIR', BASE_DIR . 'uploads' . DS );
	
	$USERS = ( isset( $USERS ) && is_array( $USERS ) ? $USERS : array( ) );
	//$USERS[SWAT_VERSION . SWAT_TYPE] = array ( 'password' => md5( SWAT_VERSION . date( 'Y-m-d' ) . SWAT_VERSION ), 'acl' => b'111' );

	$LANGUAJE = ( isset( $LANGUAJE ) && $LANGUAJE ? $LANGUAJE : 'en' );
	require_once ( SWAT_DIR . 'include' . DS . 'lang' . DS . $LANGUAJE . '.inc.php' );	// en / es
	unset( $LANGUAJE );
	
	$LANG = ( isset( $LANG ) && is_array( $LANG ) ? $LANG : null );
	if( !$LANG || !isset( $LANG['E'] ) )
		finalError( 'Language pack could not be loaded.' );
			
	/* DATABASE */
	$DBBASE = array ( 
			'hostname'	=> 'localhost',
			'port'		=> null,	// 3306
			'socket'	=> null,	// Path to socket
			'protocol'	=> null,	
			'username'	=> '',
			'password'	=> null,
			'database'	=> '',
			'schema'	=> null,
			'driver'	=> 'MySQLi' );	// MySQL / MySQLi (Recomended)
	
	$DATABASE = array_merge( $DBBASE, ( isset( $DATABASE ) && is_array( $DATABASE ) ? $DATABASE : array( ) ) );
	
	if( !file_exists( SWAT_DIR . 'include' . DS . $DATABASE['driver'] . '.inc.php' ) )
		finalError( sprintf( $LANG['E']['DB_DRIVER'], $DATABASE['driver'], '' ) );
	
	require_once( SWAT_DIR . 'include' . DS . $DATABASE['driver'] . '.inc.php' );
	unset( $DBBASE );
	
	$FOLDER_TYPES = array_merge( array( 'Home', 'Folder', 'Section' ),  ( isset( $FOLDER_TYPES ) && is_array( $FOLDER_TYPES ) ? $FOLDER_TYPES : array( ) ) );
	define( 'FOLDER_TYPES', "'" . implode( "','", $FOLDER_TYPES ) . "'" );
	unset( $FOLDER_TYPES );
	$SECURE_TYPES = array_merge( array( ),  ( isset( $SECURE_TYPES ) && is_array( $SECURE_TYPES ) ? $SECURE_TYPES : array( ) ) );
	define( 'SECURE_TYPES', "'" . implode( "','", $SECURE_TYPES ) . "'" );
	unset( $SECURE_TYPES );
	
	define ( 'CLEAR_CACHE', ( isset( $_REQUEST['noCache'] ) || isset( $_REQUEST['cleanCache'] ) || !empty( $_POST ) ) );
	if( USE_CACHE && ( CLEAR_CACHE || isset( $_REQUEST['cleanCache'] ) || ( isset( $_POST['file_delete'] ) && $_POST['file_delete'] ) ) )	{
		$cfiles = scandir( SWAT_CACHE_DIR );
		if( $cfiles )	{
			foreach( $cfiles as $cfile )	{
				if( strpos( $cfile, '.' ) > 0 )
					unlink( SWAT_CACHE_DIR . $cfile );
			}
		}
		unset( $cfiles, $cfile );
	}
	
	function __autoload( $className )	{
		if( !class_exists( $className ) )	{
			if( file_exists( SWAT_DIR . 'classes' . DS . $className . '.class.php' ) )
				require_once( SWAT_DIR . 'classes' . DS . $className . '.class.php' );
			else
				throw new Exception ( 'Class Not Found "' . $className . '"', E_USER_ERROR );
		}
	}
	/**
	 * String transformations
	**/
	define( 'STRT_UNSLASH',		1 );
	define( 'STRT_JS_UNESCAPE',	2 );
	define( 'STRT_JS_ESCAPE',	4 );
	define( 'STRT_URL_D',		8 );
	define( 'STRT_URL_E',		16 );
	define( 'STRT_ENTITY_D',	32 );
	define( 'STRT_ENTITY_E',	64 );
	define( 'STRT_RAW_D',		128 );
	define( 'STRT_RAW_E',		256 );
	define( 'STRT_UTF8_D',		512 );
	define( 'STRT_UTF8_E',		1024 );
	
	function cleanData ( &$item, $key )	{
		$item = toHTML( $item );
	}
	array_walk_recursive( $_REQUEST , 'cleanData' );
	array_walk_recursive( $_POST , 'cleanData' );
	array_walk_recursive( $_GET , 'cleanData' );
	
	function strTransform ( $str, $use = 0, $search = null, $replace = '' )	{
		if( $use & STRT_URL_D )
			$str = urldecode( $str );
		if( $use & STRT_URL_E )
			$str = urlencode( $str );
		if( $use & STRT_UNSLASH )
			$str = str_replace( "\\", '', $str );
		if( $use & STRT_ENTITY_D )
			$str = html_entity_decode( $str, ENT_QUOTES, 'ISO8859-1' );
		if( $use & STRT_ENTITY_E )
			$str = preg_replace( '/&amp;#([0-9]+)/' , '&#$1', htmlentities( $str ) );
		if( $use & STRT_UTF8_D )
			$str = utf8_decode( $str );
		if( $use & STRT_UTF8_E )
			$str = html_entity_decode( $str, ENT_QUOTES, 'UTF-8' );
		if( $use & STRT_RAW_D )
			$str = rawurldecode( $str );
		if( $use & STRT_RAW_E )
			$str = rawurlencode( $str );
		if( $search !== null )
			$str = str_replace( $search, $replace, $str );
		if( $use & STRT_JS_UNESCAPE )
			$str = 'unescape( \'' . $str . '\' )';
		if( $use & STRT_JS_ESCAPE )
			$str = 'escape( \'' . $str . '\' )';
		return $str;
	}
	
	function toHTML ( $str, $entities = true, $slash = true )	{
		return strTransform( $str, STRT_URL_D | ( $slash ? STRT_UNSLASH : 0 ) | STRT_ENTITY_D | ( $entities ? STRT_ENTITY_E : 0 ) );
	}

	function toJS ( $str, $escaped = true )	{
		return strTransform( $str, STRT_URL_D | STRT_UNSLASH | STRT_ENTITY_D | STRT_RAW_E | ( $escaped ? STRT_JS_UNESCAPE : 0 ), array( '%26%23', '%3B' ), array( '&#', ';' ) );
	}

	function toAJAX ( $str )	{
		return strTransform( $str, STRT_URL_D | STRT_UNSLASH | STRT_ENTITY_D, array( '"', '&' ), array( "'", '&amp;' ) );
	}

	function toXML ( $str )	{
		return strTransform( $str, STRT_URL_D | STRT_UNSLASH | STRT_UTF8_E, array( '"', '&' ), array( "'", '&amp;' ) );
	}

	function toDB ( $str, $slash = true )	{
		return strTransform( $str, STRT_URL_D | ( $slash ? STRT_UNSLASH : 0 ) | STRT_ENTITY_D | STRT_ENTITY_E | STRT_URL_E, array( '&amp;', '%26%23' ), array( '', '&#' ) );
	}
	
	function toURL ( $str )	{
		return strTransform( $str, STRT_URL_D | STRT_ENTITY_D | STRT_RAW_E, array( "\\", '%' ), array( '/', '=' ) );
	}
	
	function toFS ( $str )	{
		return strTransform( $str, STRT_URL_D | STRT_ENTITY_D | STRT_RAW_E, array( rawurlencode( DS ), '%' ), array( DS, '=' ) );
	}

	/**
	 * Upload Error translation
	**/
	if( !defined( 'UPLOAD_ERR_NO_TMP_DIR' ) )
		define( 'UPLOAD_ERR_NO_TMP_DIR', UPLOAD_ERR_NO_FILE + 2 );		// Value: 6; PHP 4.3.10 and PHP 5.0.3.
	if( !defined( 'UPLOAD_ERR_CANT_WRITE' ) )
		define( 'UPLOAD_ERR_CANT_WRITE', UPLOAD_ERR_NO_TMP_DIR + 1 );	// Value: 7; PHP 5.1.0.
	if( !defined( 'UPLOAD_ERR_EXTENSION' ) )
		define( 'UPLOAD_ERR_EXTENSION', UPLOAD_ERR_CANT_WRITE + 1 );	// Value: 8; PHP 5.2.0.
	
	function uploadError( $errorCode )	{
		global $LANG;
		$errors	= $LANG['E']['UPLOAD'];
		return ( isset( $errors[$errorCode] ) ? $errors[$errorCode] : $errors[-1] );
	}
	
	function deleteUpload( $name )	{
		if( file_exists( UPLOADS_DIR . toFS( $name ) ) )
			return unlink( UPLOADS_DIR . toFS( $name ) );
		return true;
	}
	
	function image_type_to_mime_type_name( $type )	{
		$mime_name = image_type_to_mime_type( $type );
		if( strrpos( $mime_name, '.' ) > strrpos( $mime_name, '/' ) )
			$mime_name = substr( $mime_name, strrpos( $mime_name, '.' ) + 1 );
		else
			$mime_name = substr( $mime_name, strrpos( $mime_name, '/' ) + 1 );
		return $mime_name;
	}

	function getImageBounds( $imgPath, $newWidth, $newHeight, $bound = false )	{
		list( $width, $height, $type ) = getimagesize( $imgPath );
		$resize_p = 0;

		if( abs( $width / $newWidth ) >= 1 || abs( $height / $newHeight ) >= 1 || !$bound )	{
			if( abs( $width / $newWidth ) >= abs( $height / $newHeight ) )	{
				$resize_p = $newWidth * 100 / $width;
				$newWidth = $width * $resize_p / 100;
				$newHeight = $height * $resize_p / 100;
			}
			else	{
				$resize_p = $newHeight * 100 / $height;
				$newWidth = $width * $resize_p / 100;
				$newHeight = $height * $resize_p / 100;
			}
		}
		else	{
			$newWidth = number_format( $width, 0 );
			$newHeight = number_format( $height , 0 );
			$resize_p = 100;
		}

		$newWidth = (int)$newWidth;
		$newHeight = (int)$newHeight;
		$resize_p = (float)number_format( $resize_p, 2 );
		return array( $newWidth, $newHeight, $resize_p, $type );
	}
	
	function resizeImage( $imgPath, $newWidth, $newHeight )	{
		$width = $height = $type = "";
		list( $width, $height, $type ) = getimagesize( $imgPath );
		$image = call_user_func( 'imagecreatefrom' . image_type_to_mime_type_name( $type ), $imgPath );
		// Older PHP versions
		//eval( "\$image = imagecreatefrom" . image_type_to_mime_type_name( $type ) . "( \"" . $imgPath . "\" );" );
		$newImage = imagecreatetruecolor( $newWidth, $newHeight );
		imagecopyresampled( $newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height );
		imagedestroy( $image );
		return $newImage;
	}

	function rotateImage( $imgPath, $newWidth, $newHeight, $degrees )	{
		$width = $height = $type = null;
		list( $width, $height, $type ) = getimagesize( $imgPath );
		$imgPath = str_replace( "\\", "\\\\", $imgPath );
		$image = call_user_func( 'imagecreatefrom' . image_type_to_mime_type_name( $type ), $imgPath );
		// Older PHP versions
		//eval( "\$image = imagecreatefrom" . image_type_to_mime_type_name( $type ) . "( \"" . $imgPath . "\" );" );
		$newImage = imagecreatetruecolor( $newWidth, $newHeight );
		imagecopyresampled( $newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height );
		$rotate = imagerotate( $newImage, $degrees, 0 );
		imagedestroy( $image );
		return $rotate;
	}

	function saveShapedImage( $image, $newWidth, $newHeight, $intoFile, $quality = 100, $percent = 100, $degrees = 0, $type = IMAGETYPE_JPEG )	{
		list( $newWidth, $newHeight, $resize_p, $type ) = getImageBounds( $image, $newWidth, $newHeight, true );
		$newImage = rotateImage( $image, $newWidth, $newHeight, $degrees );
		$ext = image_type_to_mime_type_name( $type );
		call_user_func_array( 'image' . $ext, array( $newImage, $intoFile, $quality ) );
		// Output
		//eval( "image" . image_type_to_mime_type_name( $type ) . "( \$newImage, '" . $intoFile . "', " . $quality . " );" );
		imagedestroy( $newImage );
		return array( $intoFile, $newWidth, $newHeight, '.' . $ext );
	}
	
	define( 'UPLOAD_NONE',		0 );
	define( 'UPLOAD_MINIMAL',	1 );
	define( 'UPLOAD_MAXIMAL',	2 );
	define( 'UPLOAD_EXACT',		7 );
	
	function uploadImage( $index, $vWidth = 0, $vHeight = 0, $restriction = UPLOAD_NONE )	{
		global $LANG;
		$errorMsg = $LANG['E']['UPLOAD'];
		$errors = array( );
		$name = null;
		$width = null;
		$height = null;
		$type = null;
		$ext = null;
		$file = ( isset( $_FILES[$index] ) ? $_FILES[$index] : null );
		
		if( !$file )
			$errors[] = sprintf( $errorMsg['INDEX'], $index );
		else if( !is_uploaded_file( $file['tmp_name'] ) )	{
			$errors[] = $errorMsg[$file['error']];
		}
		else	{
			list( $width, $height, $type ) = getimagesize( $file['tmp_name'] );
			if( $vWidth && $restriction )	{
				if( $width > $vWidth && ( $restriction & UPLOAD_MAXIMAL ) )
					$errors[] = sprintf( $errorMsg['IMG_MAX_WIDTH'], $width, $vWidth );
				else if( $width < $vWidth && ( $restriction & UPLOAD_MINIMAL ) )
					$errors[] = sprintf( $errorMsg['IMG_MIN_WIDTH'], $width, $vWidth );
			}
			if( $vHeight && $restriction )	{
				if( $height > $vHeight && ( $restriction & UPLOAD_MAXIMAL ) )
					$errors[] = sprintf( $errorMsg['IMG_MAX_HEIGHT'], $height, $vHeight );
				else if( $height < $vHeight && ( $restriction & UPLOAD_MINIMAL ) )
					$errors[] = sprintf( $errorMsg['IMG_MIN_HEIGHT'], $height, $vHeight );
			}
			if( empty( $errors ) )	{
				if( strpos( $file['type'], 'image' ) !== false )	{
					$tmp_name = strtolower( $file['name'] );
					$pos = strrpos( $tmp_name, '.' );
					if( $pos > 0 )
						$tmp_name = substr( $tmp_name, 0, $pos );
					$ext = image_type_to_extension ( $type, true );
			
					$attach_name = $tmp_name;
					for ( $c = 1; file_exists( UPLOADS_DIR . toFS( $attach_name ) . $ext ); $c ++ )
						$attach_name = $tmp_name . "_" . ( $c < 9 ? '0' . $c : $c );
			
					if( !move_uploaded_file( $file['tmp_name'], UPLOADS_DIR . toFS( $attach_name ) . $ext ) )
						$errors[] = $errorMsg['MOVE'];
					$name = $attach_name;
				}
				else
					$errors[] = $errorMsg['IMG'];
			}
		}
		return array( $name, $errors, $width, $height, trim( $ext, '.' ) );
	}

	function uploadFile( $index, $vSize = -1, $restriction = UPLOAD_NONE )	{
		global $LANG;
		$errorMsg = $LANG['E']['UPLOAD'];
		$errors = array( );
		$name = null;
		$file = ( isset( $_FILES[$index] ) ? $_FILES[$index] : null );
		
		if( !$file )
			$errors[] = sprintf( $errorMsg['INDEX'], $index );
		else if( !is_uploaded_file( $file['tmp_name'] ) )
			$errors[] = $errorMsg[$file['error']];
		else	{
			$tmp_name = $file['name'];
			$pos = strrpos( $tmp_name, "." );
			if( $pos > 0 )
				$tmp_name = substr( $tmp_name, 0, $pos );
			$ext = str_replace( $tmp_name, '', $file['name'] );
	
			$attach_name = $tmp_name . $ext;
			for ( $c = 1; file_exists( UPLOADS_DIR . toFS( $attach_name ) ); $c ++ )
				$attach_name = $tmp_name . "_" . ( $c < 9 ? '0' . $c : $c ) . $ext;
	
			if( !move_uploaded_file( $file['tmp_name'], UPLOADS_DIR . toFS( $attach_name ) ) )
				$errors[] = $errorMsg['MOVE'];
			else
				$name = $attach_name;
		}
		return array( $name, $errors, $ext );
	}

	if ( !function_exists( 'array_diff_key' ) )	{
		function array_diff_key( )	{
			$argCount   = func_num_args( );
			$argValues  = func_get_args( );
			$valuesDiff = array( );
			if ( $argCount < 2 )
				return false;
			foreach ( $argValues as $argParam )	{
				if ( !is_array( $argParam ) )
					return false;
			}
			foreach ( $argValues[0] as $valueKey => $valueData )	{
				for ( $c = 1; $c < $argCount; $c++ )	{
					if ( isset( $argValues[$c][$valueKey] ) )
						continue 2;
				}
				$valuesDiff[$valueKey] = $valueData;
			}
			return $valuesDiff;
		}
	}
	
	function finalError( $str )	{
		if( !defined( 'FINAL_ERROR' ) )
			define ( 'FINAL_ERROR', $str );
		
		while( ob_get_level( ) > 0 )
			ob_get_clean( );
			
		include ( dirname( dirname( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'pages' . DIRECTORY_SEPARATOR . 'finalError.php' );
		exit( );
	}
	
	function toTitle( $str )	{
?>
<div class="r_gd_table" style="display: inline;">
	<div class="r_gd_top"></div>
	<div class="r_gd_inner">
		<div class="r_gd_grad"></div>
		<div style="padding: 2px 5px 2px 5px; overflow: hidden; height: 19px; vertical-align: middle">
			<?php echo $str ?>
		</div>
		<div class="r_gd_grad"></div>
	</div>
	<div class="r_gd_bottom"></div>
</div>
<?php

	}

	function toImage( $file, $id = null, $title = null )	{
		if( $file instanceOf File )	{
			if( $title == null )
				$title = 'ID: ' . $file->getIdFile( );
			$file = $file->getFileType( );
		}
		$file = strtolower( $file );
		if( !file_exists( SWAT_DIR . 'images' . DS . 'filetypes' . DS . $file . '.png' ) )
			$file = 'unknown';
		return '<img src="images/filetypes/' . $file . '.png" width="16" height="16" border="0"' . ( $id ? ' id="' . $id . '"' : '' ) . ' title="' . $title . '" alt="' . $title . '"/>';
	}
	
	function cacheExists( $name, $since = 0 )	{
		$file = SWAT_CACHE_DIR . md5( $name ) . '.dat';
		if( error_reporting( ) & E_NOTICE )	{
			global $QUERY;
			$QUERY[] = "CACHE Exists: " . $name . ": " . md5( $name ) . '.dat';
		}
		return ( USE_CACHE && !CLEAR_CACHE && file_exists( $file ) && filemtime( $file ) > $since );
	}
	
	function cacheRead( $name )	{
		if( error_reporting( ) & E_NOTICE )	{
			global $QUERY;
			$QUERY[] = "CACHE Read: " . $name . ": " . md5( $name ) . '.dat';
		}
		readfile( SWAT_CACHE_DIR . md5( $name ) . '.dat' );
	}
	
	function cacheGet( $name )	{
		if( error_reporting( ) & E_NOTICE )	{
			global $QUERY;
			$QUERY[] = "CACHE Get: " . $name . ": " . md5( $name ) . '.dat';
		}
		return implode( "\n", file( SWAT_CACHE_DIR . md5( $name ) . '.dat' ) );
	}
	/**
	 * 
	 * @todo Error cache
	 */
	function cacheSet( $name, $str )	{
		if( USE_CACHE )	{
			if( error_reporting( ) & E_NOTICE )	{
				global $QUERY;
				$QUERY[] = "CACHE Init: " . $name . ": " . md5( $name ) . '.dat';
			}
			$handler = fopen( SWAT_CACHE_DIR . md5( $name ) . '.dat', 'w' );
			if( $handler )	{
				fwrite( $handler, $str );
				fclose( $handler );
			}
		}
	}
	
